<template>
  <div class="inventory-manage-page">
    <!-- 筛选区 -->
    <el-card class="mb-3">
      <el-form :inline="true" :model="filter" @submit.prevent>
        <el-form-item label="仓库">
          <el-select v-model="filter.warehouse" placeholder="全部仓库" clearable style="width: 160px;">
            <el-option v-for="w in warehouseList" :key="w.id" :label="w.name" :value="w.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filter.status" placeholder="全部状态" clearable style="width: 120px;">
            <el-option label="待执行" value="pending" />
            <el-option label="盘点中" value="doing" />
            <el-option label="待复核" value="review" />
            <el-option label="已完成" value="done" />
            <el-option label="已作废" value="cancel" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点类型">
          <el-select v-model="filter.type" placeholder="全部类型" clearable style="width: 120px;">
            <el-option label="全盘" value="all" />
            <el-option label="抽盘" value="partial" />
            <el-option label="按货架" value="shelf" />
            <el-option label="按商品" value="sku" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="filter.date" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px;" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="filter.keyword" placeholder="任务编号/备注/创建人" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <!-- <el-button type="primary" @click="doSearch">搜索</el-button> -->
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 操作区 -->
    <div class="mb-2 flex items-center gap-2">
      <el-button type="primary" @click="openEditDialog()">新建盘点任务</el-button>
      <el-button @click="exportData">导出</el-button>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="deleteBatch">批量作废</el-button>
    </div>
    <!-- 任务表格区 -->
    <el-card>
      <el-table :data="filteredList" border style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="任务编号" width="140" />
        <el-table-column prop="type" label="盘点类型" width="100">
          <template #default="scope">
            {{ typeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="created" label="创建时间" width="160" />
        <el-table-column prop="finished" label="完成时间" width="160" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
            <el-button size="small" type="danger" @click="deleteTask(scope.row)">作废</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-3 flex justify-center"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredList.length"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        v-model:current-page="page"
      />
    </el-card>
    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="editDialog.visible" :title="editDialog.data ? '编辑盘点任务' : '新建盘点任务'" width="500px">
      <el-form :model="editDialog.form" label-width="90px">
        <el-form-item label="仓库" required>
          <el-select v-model="editDialog.form.warehouse" placeholder="请选择仓库">
            <el-option v-for="w in warehouseList" :key="w.id" :label="w.name" :value="w.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点类型" required>
          <el-select v-model="editDialog.form.type" placeholder="请选择盘点类型" style="width: 180px;">
            <el-option label="全盘" value="all" />
            <el-option label="抽盘" value="partial" />
            <el-option label="按货架" value="shelf" />
            <el-option label="按商品" value="sku" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editDialog.form.type==='partial'" label="盘点范围" required>
          <el-select v-model="editDialog.form.scope" multiple placeholder="请选择盘点内容" style="width: 300px;">
            <el-option v-for="s in shelfOptions" :key="s.id" :label="s.name" :value="s.name" />
            <el-option v-for="sku in skuOptions" :key="sku.id" :label="sku.name" :value="sku.name" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editDialog.form.type==='shelf'" label="盘点货架" required>
          <el-select v-model="editDialog.form.scope" multiple placeholder="请选择货架" style="width: 300px;">
            <el-option v-for="s in shelfOptions" :key="s.id" :label="s.name" :value="s.name" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editDialog.form.type==='sku'" label="盘点商品" required>
          <el-select v-model="editDialog.form.scope" multiple placeholder="请选择商品" style="width: 300px;">
            <el-option v-for="sku in skuOptions" :key="sku.id" :label="sku.name" :value="sku.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" required>
          <el-select v-model="editDialog.form.owner" placeholder="请选择负责人" style="width: 180px;">
            <el-option v-for="s in staffList" :key="s.id" :label="s.name" :value="s.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editDialog.form.remark" type="textarea" maxlength="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveTask">保存</el-button>
      </template>
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialog.visible" title="盘点任务详情" width="900px">
      <el-tabs v-model="detailTab">
        <el-tab-pane label="基本信息" name="base">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="任务编号">{{ detailDialog.data?.code }}</el-descriptions-item>
            <el-descriptions-item label="盘点类型">{{ typeText(detailDialog.data?.type) }}</el-descriptions-item>
            <el-descriptions-item label="仓库">{{ detailDialog.data?.warehouseName }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ statusText(detailDialog.data?.status) }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ detailDialog.data?.creator }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{ detailDialog.data?.owner }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailDialog.data?.created }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">{{ detailDialog.data?.finished }}</el-descriptions-item>
            <el-descriptions-item label="盘点范围" :span="2">{{ detailDialog.data?.scope }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detailDialog.data?.remark }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="盘点明细" name="detail">
          <!-- 扫码输入区域 -->
          <div v-if="isDoing" class="barcode-input-area mb-3">
            <el-input
              v-model="barcodeInput"
              placeholder="请使用扫码枪扫描物流单号（演示模式：可直接输入单号后按回车）"
              @keyup="handleBarcodeInput"
              ref="barcodeInputRef"
              class="barcode-input"
              size="large"
            >
              <template #prepend>
                <el-icon><Scan /></el-icon>
              </template>
            </el-input>
            
            <!-- 扫码状态指示 -->
            <div class="scan-status mt-2">
              <el-tag v-if="lastScannedProduct" type="success" size="large">
                已扫描：{{ lastScannedProduct.name }}
              </el-tag>
              <el-tag v-if="scanCount > 0" type="info" size="large" class="ml-2">
                已扫描 {{ scanCount }} 个商品
              </el-tag>
            </div>
            
            <!-- 扫码快捷操作 -->
            <div class="scan-actions mt-2">
              <el-button size="small" @click="showScanHistory" type="info">
                <el-icon><Clock /></el-icon>
                扫码历史 (Ctrl+S)
              </el-button>
              <el-button size="small" @click="resetBarcodeInput" type="warning">
                <el-icon><Refresh /></el-icon>
                重新开始 (Ctrl+R)
              </el-button>
              <el-button size="small" @click="showDemoBarcodes" type="primary">
                <el-icon><View /></el-icon>
                演示单号
              </el-button>
            </div>
          </div>
          
          <div class="mb-2 flex items-center gap-2">
            <el-button v-if="detailDialog.data?.status==='pending'" type="primary" @click="startInventory">开始盘点</el-button>
            <el-button @click="downloadDetailTemplate">下载明细模板</el-button>
            <el-button type="primary" @click="importDetail" :disabled="!isDoing">导入</el-button>
            <el-button @click="exportDetail">导出</el-button>
            <el-button type="info" @click="viewDeleteRecords" v-if="deleteRecords[detailDialog.data?.id]?.length">查看删除记录</el-button>
            <el-button type="success" @click="finishInventory" v-if="isDoing">盘点完成</el-button>
          </div>
          <el-table :data="currentDetailList" border style="width:100%">
            <el-table-column prop="location" label="库位" width="120" />
            <el-table-column prop="sku" label="商品" width="160" />
            <el-table-column prop="sysQty" label="系统库存" width="100" />
            <el-table-column prop="realQty" label="实盘数量" width="100">
              <template #default="scope">
                <span v-if="isDoing && !isReviewingOrDone">
                  <el-input-number v-model="scope.row.realQty" :min="0" size="small" @change="onRealQtyInput" />
                </span>
                <span v-else>{{ scope.row.realQty }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="diff" label="盈亏" width="100">
              <template #default="scope">
                <span :style="{color: (scope.row.realQty - scope.row.sysQty) > 0 ? '#21ba45' : (scope.row.realQty - scope.row.sysQty) < 0 ? '#f5222d' : ''}">
                  {{ scope.row.realQty - scope.row.sysQty }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120">
              <template #default="scope">
                <span v-if="isDoing && !isReviewingOrDone">
                  <el-input v-model="scope.row.remark" size="small" @change="onRealQtyInput" />
                </span>
                <span v-else>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button size="small" @click="openDetailEditDialog(scope.row)" :disabled="isReviewingOrDone">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteDetail(scope.row)" :disabled="isReviewingOrDone">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="复核" name="review">
          <el-card>
            <div class="mb-2">盈亏总数：<b>{{ reviewStats.totalDiff }}</b>，差异率：<b>{{ reviewStats.diffRate }}%</b></div>
            <el-button type="primary" @click="exportReviewReport" class="mb-2">导出盘点报告</el-button>
            <el-table :data="currentDetailList" border size="small">
              <el-table-column prop="location" label="库位" width="120" />
              <el-table-column prop="sku" label="商品" width="160" />
              <el-table-column prop="sysQty" label="系统库存" width="100" />
              <el-table-column prop="realQty" label="实盘数量" width="100" />
              <el-table-column prop="diff" label="盈亏" width="100">
                <template #default="scope">
                  <span :style="{color: (scope.row.realQty - scope.row.sysQty) > 0 ? '#21ba45' : (scope.row.realQty - scope.row.sysQty) < 0 ? '#f5222d' : ''}">
                    {{ scope.row.realQty - scope.row.sysQty }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="120" />
            </el-table>
            <div class="mt-3 flex gap-2">
              <el-button type="primary" @click="approveReview" v-if="detailDialog.data?.status==='review'">复核通过</el-button>
              <el-button type="danger" @click="rejectReview" v-if="detailDialog.data?.status==='review'">驳回</el-button>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 删除记录弹窗 -->
    <el-dialog v-model="deleteRecordsDialog.visible" title="删除记录" width="800px">
      <el-table :data="deleteRecordsDialog.data" border size="small">
        <el-table-column prop="location" label="库位" width="120" />
        <el-table-column prop="sku" label="商品" width="160" />
        <el-table-column prop="sysQty" label="系统库存" width="100" />
        <el-table-column prop="realQty" label="实盘数量" width="100" />
        <el-table-column prop="reason" label="删除原因" min-width="150" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column prop="deleteTime" label="删除时间" width="160" />
      </el-table>
      <template #footer>
        <el-button @click="deleteRecordsDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 明细编辑弹窗 -->
    <el-dialog v-model="detailEditDialog.visible" :title="detailEditDialog.data ? '编辑明细' : '新增明细'" width="400px">
      <el-form :model="detailEditDialog.form" label-width="80px">
        <el-form-item label="库位" required>
          <el-input v-model="detailEditDialog.form.location" />
        </el-form-item>
        <el-form-item label="商品" required>
          <el-input v-model="detailEditDialog.form.sku" />
        </el-form-item>
        <el-form-item label="系统库存">
          <el-input-number v-model="detailEditDialog.form.sysQty" :min="0" />
        </el-form-item>
        <el-form-item label="实盘数量">
          <el-input-number v-model="detailEditDialog.form.realQty" :min="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="detailEditDialog.form.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="detailEditDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveDetail">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 扫码快速输入弹窗 -->
    <el-dialog v-model="quickInputDialog.visible" title="扫码盘库" width="500px">
      <div class="scanned-product-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品名称">
            {{ quickInputDialog.product?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="物流单号">
            {{ quickInputDialog.product?.trackingNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="库位">
            {{ quickInputDialog.detail?.location }}
          </el-descriptions-item>
          <el-descriptions-item label="系统库存">
            {{ quickInputDialog.detail?.sysQty }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商">
            {{ quickInputDialog.product?.supplier }}
          </el-descriptions-item>
          <el-descriptions-item label="预期数量">
            {{ quickInputDialog.product?.quantity }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-form :model="quickInputDialog.form" label-width="100px" class="mt-3">
        <el-form-item label="实盘数量" required>
          <el-input-number 
            v-model="quickInputDialog.form.realQty" 
            :min="0" 
            style="width: 200px"
            ref="realQtyInputRef"
            @keyup.enter="confirmQuickInput"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="quickInputDialog.form.remark" 
            placeholder="可选"
            @keyup.enter="confirmQuickInput"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="quickInputDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmQuickInput">确认</el-button>
      </template>
    </el-dialog>
    
    <!-- 扫码历史弹窗 -->
    <el-dialog v-model="scanHistoryDialog.visible" title="扫码历史" width="800px">
      <el-table :data="scanHistoryDialog.data" border size="small">
        <el-table-column prop="timestamp" label="扫码时间" width="160" />
        <el-table-column prop="product" label="商品名称" width="200" />
        <el-table-column prop="trackingNumber" label="物流单号" width="150" />
        <el-table-column prop="realQty" label="实盘数量" width="100" />
        <el-table-column prop="operator" label="操作人" width="100" />
      </el-table>
      <template #footer>
        <el-button @click="scanHistoryDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 演示单号弹窗 -->
    <el-dialog v-model="demoBarcodesDialog.visible" title="演示物流单号" width="600px">
      <div class="demo-barcodes-content">
        <p class="demo-tip">💡 <strong>演示说明：</strong></p>
        <p class="demo-tip">1. 点击下方物流单号可复制到输入框</p>
        <p class="demo-tip">2. 按回车键或点击"模拟扫码"按钮</p>
        <p class="demo-tip">3. 体验完整的扫码入库流程</p>
        
        <div class="barcode-list">
          <div 
            v-for="product in productDatabase" 
            :key="product.trackingNumber"
            class="barcode-item"
            @click="selectDemoBarcode(product.trackingNumber)"
          >
            <div class="barcode-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="barcode-code">{{ product.trackingNumber }}</div>
            </div>
            <el-button size="small" type="primary" @click.stop="simulateScan(product.trackingNumber)">
              模拟扫码
            </el-button>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="demoBarcodesDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx';
import { useAuthStore } from '@/store/auth'
const auth = useAuthStore()
// mock仓库数据
const warehouseList = ref([
  { id: 1, name: '上海仓' },
  { id: 2, name: '北京仓' }
])
// mock员工数据
const staffList = ref([
  { id: 'S001', name: '张三' },
  { id: 'S002', name: '李四' },
  { id: 'S003', name: '王五' }
])
// mock货架、商品数据
const shelfOptions = ref([
  { id: 'A1', name: 'A1货架' },
  { id: 'A2', name: 'A2货架' },
  { id: 'B1', name: 'B1货架' }
])
const skuOptions = ref([
  { id: 'SKU001', name: '商品A' },
  { id: 'SKU002', name: '商品B' },
  { id: 'SKU003', name: '商品C' }
])
// mock盘点任务数据
const taskList = ref([
  { id: 1, code: 'PD20240601001', type: 'all', warehouse: 1, warehouseName: '上海仓', status: 'pending', creator: '张三', owner: '李四', created: '2024-06-01 10:00', finished: '', scope: '全仓', remark: '月度全盘' },
  { id: 2, code: 'PD20240601002', type: 'partial', warehouse: 2, warehouseName: '北京仓', status: 'doing', creator: '王五', owner: '赵六', created: '2024-06-02 09:00', finished: '', scope: 'A区/B区', remark: '' },
  { id: 3, code: 'PD20240601003', type: 'shelf', warehouse: 1, warehouseName: '上海仓', status: 'done', creator: '张三', owner: '李四', created: '2024-05-28 14:00', finished: '2024-05-29 16:00', scope: 'A1货架', remark: '' }
])
const filter = ref({ warehouse: '', status: '', type: '', date: '', keyword: '' })
const page = ref(1)
const pageSize = ref(20)
const multipleSelection = ref<any[]>([])
const filteredList = computed(() => {
  let list = taskList.value
  if (filter.value.warehouse) list = list.filter(l => l.warehouse === filter.value.warehouse)
  if (filter.value.status) list = list.filter(l => l.status === filter.value.status)
  if (filter.value.type) list = list.filter(l => l.type === filter.value.type)
  if (filter.value.date && filter.value.date.length === 2) {
    const [start, end] = filter.value.date
    list = list.filter(l => {
      const created = new Date(l.created).getTime()
      return created >= new Date(start).getTime() && created <= new Date(end).getTime()
    })
  }
  if (filter.value.keyword) {
    const k = filter.value.keyword.trim()
    list = list.filter(l => l.code.includes(k) || l.remark.includes(k) || l.creator.includes(k))
  }
  // 分页（简单模拟）
  const start = (page.value - 1) * 20
  return list.slice(start, start + 20)
})
function doSearch() { page.value = 1 }
function resetFilter() { filter.value = { warehouse: '', status: '', type: '', date: '', keyword: '' }; page.value = 1 }
function onSelectionChange(val: any[]) { multipleSelection.value = val }
// 新建/编辑弹窗
const editDialog = ref({ visible: false, data: null as any, form: { warehouse: '', type: '', scope: '', owner: '', remark: '' } })
function openEditDialog(row?: any) {
  if (row) {
    editDialog.value.data = row
    editDialog.value.form = { ...row }
  } else {
    editDialog.value.data = null
    editDialog.value.form = { warehouse: '', type: '', scope: '', owner: '', remark: '' }
  }
  editDialog.value.visible = true
}
// mock当前库存数据（实际应从库存表获取）
const stockList = ref([
  { location: 'A1-01', sku: '商品A', sysQty: 100 },
  { location: 'A1-02', sku: '商品B', sysQty: 50 },
  { location: 'B1-01', sku: '商品C', sysQty: 80 }
])
// mock盘点明细数据
const detailMap = ref<Record<number, any[]>>({
  1: [
    { id: 1, location: 'A1-01', sku: '商品A', sysQty: 100, realQty: 98, remark: '包装破损' },
    { id: 2, location: 'A1-02', sku: '商品B', sysQty: 50, realQty: 50, remark: '' },
    { id: 3, location: 'A1-03', sku: '商品D', sysQty: 120, realQty: 115, remark: '部分过期' },
    { id: 4, location: 'A2-01', sku: '商品E', sysQty: 80, realQty: 82, remark: '多出2件' },
    { id: 5, location: 'A2-02', sku: '商品F', sysQty: 60, realQty: 60, remark: '' }
  ],
  2: [
    { id: 1, location: 'B1-01', sku: '商品C', sysQty: 80, realQty: 80, remark: '' },
    { id: 2, location: 'B1-02', sku: '商品G', sysQty: 90, realQty: 88, remark: '包装损坏' },
    { id: 3, location: 'B2-01', sku: '商品H', sysQty: 150, realQty: 150, remark: '' }
  ],
  3: [
    { id: 1, location: 'C1-01', sku: '商品I', sysQty: 200, realQty: 195, remark: '库存差异' },
    { id: 2, location: 'C1-02', sku: '商品J', sysQty: 75, realQty: 75, remark: '' },
    { id: 3, location: 'C2-01', sku: '商品K', sysQty: 110, realQty: 112, remark: '多出2件' },
    { id: 4, location: 'C2-02', sku: '商品L', sysQty: 85, realQty: 83, remark: '包装破损' }
  ]
})

// 扫码相关变量
const barcodeInput = ref('')
const barcodeInputRef = ref()
const realQtyInputRef = ref()
const lastScannedProduct = ref<any>(null)
const scanCount = ref(0)
const scanHistory = ref<any[]>([])

// 扫码快速输入弹窗
const quickInputDialog = ref({
  visible: false,
  product: null as any,
  detail: null as any,
  form: {
    realQty: 0,
    remark: ''
  }
})

// 扫码历史弹窗
const scanHistoryDialog = ref({
  visible: false,
  data: [] as any[]
})

// 演示条码弹窗
const demoBarcodesDialog = ref({
  visible: false
})

// 模拟商品数据（根据物流单号查询）
const productDatabase = ref([
  { trackingNumber: 'SF1234567890', name: '商品A', sku: '商品A', quantity: 100, supplier: '供应商A' },
  { trackingNumber: 'SF1234567891', name: '商品B', sku: '商品B', quantity: 50, supplier: '供应商B' },
  { trackingNumber: 'SF1234567892', name: '商品C', sku: '商品C', quantity: 80, supplier: '供应商C' },
  { trackingNumber: 'SF1234567893', name: '商品D', sku: '商品D', quantity: 120, supplier: '供应商A' },
  { trackingNumber: 'SF1234567894', name: '商品E', sku: '商品E', quantity: 80, supplier: '供应商B' },
  { trackingNumber: 'SF1234567895', name: '商品F', sku: '商品F', quantity: 60, supplier: '供应商C' },
  { trackingNumber: 'SF1234567896', name: '商品G', sku: '商品G', quantity: 90, supplier: '供应商A' },
  { trackingNumber: 'SF1234567897', name: '商品H', sku: '商品H', quantity: 150, supplier: '供应商B' },
  { trackingNumber: 'SF1234567898', name: '商品I', sku: '商品I', quantity: 200, supplier: '供应商C' },
  { trackingNumber: 'SF1234567899', name: '商品J', sku: '商品J', quantity: 75, supplier: '供应商A' },
  { trackingNumber: 'SF1234567900', name: '商品K', sku: '商品K', quantity: 110, supplier: '供应商B' },
  { trackingNumber: 'SF1234567901', name: '商品L', sku: '商品L', quantity: 85, supplier: '供应商C' }
])
function saveTask() {
  const f = editDialog.value.form
  if (!f.warehouse) return ElMessage.warning('请选择仓库')
  if (!f.type) return ElMessage.warning('请选择盘点类型')
  if (!f.owner) return ElMessage.warning('请选择负责人')
  if (editDialog.value.data) {
    // 编辑
    const idx = taskList.value.findIndex(t => t.id === editDialog.value.data.id)
    if (idx > -1) taskList.value[idx] = { ...f, id: editDialog.value.data.id, code: editDialog.value.data.code, warehouseName: getWarehouseName(f.warehouse), status: editDialog.value.data.status, creator: editDialog.value.data.creator, created: editDialog.value.data.created, finished: editDialog.value.data.finished }
    ElMessage.success('编辑成功')
  } else {
    // 新建
    const newId = Date.now()
    const code = 'PD' + new Date().toISOString().slice(0,10).replace(/-/g,'') + Math.floor(Math.random()*1000).toString().padStart(3,'0')
    const creator = auth.user?.name || '未知用户'
    taskList.value.unshift({ ...f, id: newId, code, warehouseName: getWarehouseName(f.warehouse), status: 'pending', creator, created: new Date().toLocaleString(), finished: '', type: typeText(f.type) })
    // 自动生成明细（mock：全盘拉全部库存，后续可按范围筛选）
    detailMap.value[newId] = stockList.value.map(s => ({
      id: Date.now() + Math.floor(Math.random()*10000),
      location: s.location,
      sku: s.sku,
      sysQty: s.sysQty,
      realQty: null,
      remark: ''
    }))
    ElMessage.success('新建成功')
  }
  editDialog.value.visible = false
}
function canCancelTask(task: { status: string }) {
  // 只允许作废 pending、review 状态的任务
  return task.status !== 'done' && task.status !== 'doing'
}
function deleteTask(row: { id: number, status: string }) {
  if (!canCancelTask(row)) {
    ElMessage.error('已完成或盘点中的任务不允许作废！')
    return
  }
  ElMessageBox.confirm('确定要作废该盘点任务吗？', '提示', { type: 'warning' })
    .then(() => {
      const idx = taskList.value.findIndex(t => t.id === row.id)
      if (idx > -1) taskList.value[idx].status = 'cancel'
      ElMessage.success('已作废')
    })
    .catch(() => {})
}
function deleteBatch() {
  if (!multipleSelection.value.length) return
  // 校验选中任务是否有已完成或盘点中状态
  if (multipleSelection.value.some(t => t.status === 'done' || t.status === 'doing')) {
    ElMessage.error('选中的任务中包含已完成或盘点中的任务，无法批量作废！')
    return
  }
  ElMessageBox.confirm('确定要批量作废选中的盘点任务吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map(t => t.id)
      taskList.value.forEach(t => { if (ids.includes(t.id)) t.status = 'cancel' })
      ElMessage.success('批量作废成功')
      multipleSelection.value = []
    })
    .catch(() => {})
}
function exportData() {
  // 判断是否有勾选任务
  const exportTasks = multipleSelection.value.length > 0 ? multipleSelection.value : filteredList.value
  const header = [
    '任务编号', '盘点类型', '仓库', '状态', '创建人', '负责人', '创建时间', '完成时间', '盘点范围', '备注',
    '明细-库位', '明细-商品', '明细-系统库存', '明细-实盘数量', '明细-盈亏', '明细-备注',
    '复核-盈亏总数', '复核-差异率(%)'
  ]
  const rows = []
  exportTasks.forEach(task => {
    const details = detailMap.value[task.id] || []
    // 复核统计
    const totalDiff = details.reduce((sum, row) => sum + ((row.realQty ?? 0) - (row.sysQty ?? 0)), 0)
    const totalSys = details.reduce((sum, row) => sum + (row.sysQty ?? 0), 0)
    const diffRate = totalSys ? ((totalDiff / totalSys) * 100).toFixed(2) : '0.00'
    if (details.length === 0) {
      rows.push([
        task.code, task.type, task.warehouseName, statusText(task.status), task.creator, task.owner, task.created, task.finished, task.scope, task.remark,
        '', '', '', '', '', '', totalDiff, diffRate
      ])
    } else {
      details.forEach((d, idx) => {
        rows.push([
          idx === 0 ? task.code : '',
          idx === 0 ? task.type : '',
          idx === 0 ? task.warehouseName : '',
          idx === 0 ? statusText(task.status) : '',
          idx === 0 ? task.creator : '',
          idx === 0 ? task.owner : '',
          idx === 0 ? task.created : '',
          idx === 0 ? task.finished : '',
          idx === 0 ? task.scope : '',
          idx === 0 ? task.remark : '',
          d.location, d.sku, d.sysQty, d.realQty, (d.realQty ?? 0) - (d.sysQty ?? 0), d.remark,
          idx === 0 ? totalDiff : '',
          idx === 0 ? diffRate : ''
        ])
      })
    }
  })
  const ws = XLSX.utils.aoa_to_sheet([header, ...rows])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '盘点任务')
  XLSX.writeFile(wb, '库存盘点任务及明细.xlsx')
}
const detailDialog = ref({ visible: false, data: null as any })
const detailTab = ref('base')
const currentDetailList = computed(() => {
  const id = detailDialog.value.data?.id;
  let list = id ? (detailMap.value[id] || []) : [];
  // 根据任务类型和范围过滤明细
  const task = detailDialog.value.data;
  if (task && task.scope) {
    if (task.type === 'sku' && task.scope !== '全仓') {
      // 按商品类型：只显示指定商品的明细
      const scopeItems = task.scope.split(',').map(s => s.trim());
      list = list.filter(item => scopeItems.includes(item.sku));
    } else if (task.type === 'shelf' && task.scope !== '全仓') {
      // 按货架类型：只显示指定货架的明细
      const scopeItems = task.scope.split(',').map(s => s.trim());
      list = list.filter(item => scopeItems.some(shelf => item.location.startsWith(shelf)));
    }
    // 全盘和抽盘类型显示所有明细
  }
  return list;
});
const detailEditDialog = ref({ visible: false, data: null as any, form: { location: '', sku: '', sysQty: 0, realQty: 0, remark: '' } })
const deleteRecordsDialog = ref({ visible: false, data: [] as any[] })
function viewDetail(row: any) {
  detailDialog.value.data = row
  detailDialog.value.visible = true
}

function viewDeleteRecords() {
  const id = detailDialog.value.data?.id
  if (!id) return
  deleteRecordsDialog.value.data = deleteRecords.value[id] || []
  deleteRecordsDialog.value.visible = true
}
function statusText(status: string) {
  switch (status) {
    case 'pending': return '待执行'
    case 'doing': return '盘点中'
    case 'review': return '待复核'
    case 'done': return '已完成'
    case 'cancel': return '已作废'
    default: return status
  }
}
function statusTagType(status: string) {
  switch (status) {
    case 'pending': return 'info'
    case 'doing': return 'primary'
    case 'review': return 'warning'
    case 'done': return 'success'
    case 'cancel': return 'danger'
    default: return ''
  }
}
function typeText(type: string) {
  switch (type) {
    case 'all': return '全盘'
    case 'partial': return '抽盘'
    case 'shelf': return '按货架'
    case 'sku': return '按商品'
    default: return type
  }
}
function getWarehouseName(id: number) {
  const w = warehouseList.value.find(w => w.id === id)
  return w ? w.name : ''
}
function openDetailEditDialog(row?: any) {
  if (row) {
    detailEditDialog.value.data = row
    detailEditDialog.value.form = { ...row }
  } else {
    detailEditDialog.value.data = null
    detailEditDialog.value.form = { location: '', sku: '', sysQty: 0, realQty: 0, remark: '' }
  }
  detailEditDialog.value.visible = true
}
function saveDetail() {
  const f = detailEditDialog.value.form
  if (!f.location) return ElMessage.warning('请输入库位')
  if (!f.sku) return ElMessage.warning('请输入商品')
  const id = detailDialog.value.data?.id
  if (!id) return
  if (detailEditDialog.value.data) {
    // 编辑
    const idx = detailMap.value[id].findIndex((d: any) => d.id === detailEditDialog.value.data.id)
    if (idx > -1) detailMap.value[id][idx] = { ...f, id: detailEditDialog.value.data.id }
    ElMessage.success('编辑成功')
  } else {
    // 新增
    const newId = Date.now()
    detailMap.value[id].push({ ...f, id: newId })
    ElMessage.success('新增成功')
  }
  detailEditDialog.value.visible = false
}
// 删除记录存储
const deleteRecords = ref<Record<number, any[]>>({})

function deleteDetail(row: any) {
  const id = detailDialog.value.data?.id
  if (!id) return
  
  // 弹出删除原因输入框
  ElMessageBox.prompt('请输入删除原因', '删除商品', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '删除原因不能为空'
  }).then(({ value: reason }) => {
    // 记录删除操作
    if (!deleteRecords.value[id]) {
      deleteRecords.value[id] = []
    }
    deleteRecords.value[id].push({
      id: Date.now(),
      location: row.location,
      sku: row.sku,
      sysQty: row.sysQty,
      realQty: row.realQty,
      reason: reason,
      operator: auth.user?.name || '未知用户',
      deleteTime: new Date().toLocaleString()
    })
    
    // 从明细中删除
    detailMap.value[id] = detailMap.value[id].filter((d: any) => d.id !== row.id)
    ElMessage.success('删除成功，已记录操作')
  }).catch(() => {
    // 用户取消删除
  })
}
// 明细tab不允许手动新增/删除，只能录入/导入实盘数量和备注
// 移除明细tab的新增、删除按钮，只保留导入、导出
function downloadDetailTemplate() {
  const id = detailDialog.value.data?.id;
  if (!id) return;
  const data = (detailMap.value[id] || []).map(row => [row.location, row.sku, row.sysQty, '', '']);
  const header = ['库位', '商品', '系统库存', '实盘数量', '备注'];
  const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '盘点明细模板');
  XLSX.writeFile(wb, '盘点明细模板.xlsx');
}
function importDetail() {
  // 支持Excel导入，批量填充实盘数量
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx,.xls';
  input.onchange = async (e: any) => {
    const file = e.target.files[0];
    if (!file) return;
    const data = await file.arrayBuffer();
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(sheet);
    const id = detailDialog.value.data?.id;
    if (!id) return;
    let count = 0;
    rows.forEach((row: any) => {
      const location = row['库位'] || row['location'];
      const sku = row['商品'] || row['sku'];
      const realQty = row['实盘数量'] || row['realQty'];
      const remark = row['备注'] || row['remark'] || '';
      const detail = detailMap.value[id].find((d: any) => d.location === location && d.sku === sku);
      if (detail) {
        detail.realQty = Number(realQty);
        detail.remark = remark;
        count++;
      }
    });
    ElMessage.success(`导入成功，已更新${count}条`);
  };
  input.click();
  // 首次导入时自动变更为盘点中
  if (detailDialog.value.data?.status === 'pending') {
    startInventory();
  }
}
function exportDetail() {
  const id = detailDialog.value.data?.id;
  if (!id) return;
  const data = (detailMap.value[id] || []).map(row => [row.location, row.sku, row.sysQty, row.realQty ?? '', row.realQty !== null ? row.realQty - row.sysQty : '', row.remark || '']);
  const header = ['库位', '商品', '系统库存', '实盘数量', '盈亏', '备注'];
  
  // 如果有删除记录，添加到导出中
  const deleteData = (deleteRecords.value[id] || []).map(row => [row.location, row.sku, row.sysQty, row.realQty ?? '', '已删除', row.reason, row.operator, row.deleteTime]);
  const deleteHeader = ['库位', '商品', '系统库存', '实盘数量', '状态', '删除原因', '操作人', '删除时间'];
  
  const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '盘点明细');
  
  // 如果有删除记录，创建第二个sheet
  if (deleteData.length > 0) {
    const wsDelete = XLSX.utils.aoa_to_sheet([deleteHeader, ...deleteData]);
    XLSX.utils.book_append_sheet(wb, wsDelete, '删除记录');
  }
  
  XLSX.writeFile(wb, '盘点明细.xlsx');
}
const isReviewingOrDone = computed(() => detailDialog.value.data?.status === 'review' || detailDialog.value.data?.status === 'done');
const isDoing = computed(() => detailDialog.value.data?.status === 'doing');
const reviewStats = computed(() => {
  const list = currentDetailList.value;
  const totalDiff = list.reduce((sum, row) => sum + ((row.realQty ?? 0) - (row.sysQty ?? 0)), 0);
  const totalSys = list.reduce((sum, row) => sum + (row.sysQty ?? 0), 0);
  const diffRate = totalSys ? ((totalDiff / totalSys) * 100).toFixed(2) : '0.00';
  return { totalDiff, diffRate };
});
function startInventory() {
  if (!detailDialog.value.data) return;
  const id = detailDialog.value.data.id;
  const idx = taskList.value.findIndex(t => t.id === id);
  if (idx > -1) {
    taskList.value[idx].status = 'doing';
    detailDialog.value.data.status = 'doing';
    ElMessage.success('已进入盘点中');
  }
}
function onRealQtyInput() {
  // 首次录入/导入时自动变更为盘点中
  if (detailDialog.value.data?.status === 'pending') {
    startInventory();
  }
}
function finishInventory() {
  if (!detailDialog.value.data) return;
  const id = detailDialog.value.data.id;
  // 变更任务状态为待复核
  const idx = taskList.value.findIndex(t => t.id === id);
  if (idx > -1) {
    taskList.value[idx].status = 'review';
    detailDialog.value.data.status = 'review';
    ElMessage.success('已提交复核');
  }
}
function approveReview() {
  if (!detailDialog.value.data) return;
  const id = detailDialog.value.data.id;
  const idx = taskList.value.findIndex(t => t.id === id);
  if (idx > -1) {
    taskList.value[idx].status = 'done';
    taskList.value[idx].finished = new Date().toLocaleString();
    detailDialog.value.data.status = 'done';
    detailDialog.value.data.finished = taskList.value[idx].finished;
    ElMessage.success('复核通过，盘点已完成');
  }
}
function rejectReview() {
  if (!detailDialog.value.data) return;
  const id = detailDialog.value.data.id;
  const idx = taskList.value.findIndex(t => t.id === id);
  if (idx > -1) {
    taskList.value[idx].status = 'doing';
    detailDialog.value.data.status = 'doing';
    ElMessage.success('已驳回，返回盘点中');
  }
}
function exportReviewReport() {
  const task = detailDialog.value.data;
  if (!task) return;
  const id = task.id;
  const detail = detailMap.value[id] || [];
  const header = ['库位', '商品', '系统库存', '实盘数量', '盈亏', '备注'];
  const data = detail.map(row => [row.location, row.sku, row.sysQty, row.realQty ?? '', row.realQty !== null ? row.realQty - row.sysQty : '', row.remark || '']);
  // 任务信息和统计
  const info = [
    ['任务编号', task.code],
    ['盘点类型', task.type],
    ['仓库', task.warehouseName],
    ['状态', statusText(task.status)],
    ['创建人', task.creator],
    ['负责人', task.owner],
    ['创建时间', task.created],
    ['完成时间', task.finished || ''],
    ['盘点范围', task.scope],
    ['备注', task.remark],
    ['盈亏总数', reviewStats.value.totalDiff],
    ['差异率', reviewStats.value.diffRate + '%']
  ];
  const ws = XLSX.utils.aoa_to_sheet([...info, [], header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '盘点报告');
  XLSX.writeFile(wb, `盘点报告_${task.code}.xlsx`);
}

// ========== 扫码相关方法 ==========

// 物流单号格式验证
function validateTrackingNumber(trackingNumber: string): boolean {
  // 支持多种物流单号格式
  const patterns = [
    /^SF\d{10}$/, // 顺丰单号
    /^YT\d{10}$/, // 圆通单号
    /^STO\d{10}$/, // 申通单号
    /^ZTO\d{10}$/, // 中通单号
    /^YTO\d{10}$/, // 韵达单号
    /^[A-Z]{2,4}\d{8,12}$/, // 通用物流单号格式
  ]
  
  return patterns.some(pattern => pattern.test(trackingNumber))
}

// 查询商品信息
function queryProductByTrackingNumber(trackingNumber: string) {
  return productDatabase.value.find(product => product.trackingNumber === trackingNumber)
}

// 查找盘点明细
function findInventoryDetail(sku: string) {
  const id = detailDialog.value.data?.id
  if (!id) return null
  return detailMap.value[id]?.find(item => item.sku === sku)
}

// 处理扫码输入
function handleBarcodeInput(event: KeyboardEvent) {
  // 扫码枪通常以回车键结束
  if (event.key === 'Enter') {
    const barcode = barcodeInput.value.trim()
    if (barcode) {
      processBarcode(barcode)
      barcodeInput.value = ''
    }
  }
}

// 处理扫码结果
async function processBarcode(trackingNumber: string) {
  try {
    // 1. 验证物流单号格式
    if (!validateTrackingNumber(trackingNumber)) {
      ElMessage.error('无效的物流单号格式')
      return
    }
    
    // 2. 查询商品信息
    const product = queryProductByTrackingNumber(trackingNumber)
    if (!product) {
      ElMessage.error('未找到该物流单号对应的商品')
      return
    }
    
    // 3. 查找盘点明细
    const detail = findInventoryDetail(product.sku)
    if (!detail) {
      ElMessage.warning('该商品不在本次盘点范围内')
      return
    }
    
    // 4. 更新扫码状态
    lastScannedProduct.value = product
    scanCount.value++
    
    // 5. 显示快速输入弹窗
    showQuickInputDialog(detail, product)
    
    // 6. 播放成功提示音
    playScanSound(true)
    
  } catch (error) {
    ElMessage.error('扫码处理失败：' + (error as Error).message)
    playScanSound(false)
  }
}

// 显示快速输入弹窗
function showQuickInputDialog(detail: any, product: any) {
  quickInputDialog.value = {
    visible: true,
    product,
    detail,
    form: {
      realQty: detail.realQty || 0,
      remark: detail.remark || ''
    }
  }
  
  // 自动聚焦到数量输入框
  nextTick(() => {
    const inputRef = realQtyInputRef.value
    if (inputRef) {
      inputRef.focus()
    }
  })
}

// 确认快速输入
function confirmQuickInput() {
  const { product, detail, form } = quickInputDialog.value
  
  // 更新盘点明细
  const id = detailDialog.value.data?.id
  if (!id) return
  
  const detailList = detailMap.value[id]
  const index = detailList.findIndex(item => item.id === detail.id)
  if (index > -1) {
    detailList[index] = {
      ...detail,
      realQty: form.realQty,
      remark: form.remark
    }
  }
  
  // 记录扫码历史
  addScanHistory(product, form.realQty)
  
  // 关闭弹窗并清空扫码输入
  quickInputDialog.value.visible = false
  barcodeInput.value = ''
  
  // 重新聚焦到扫码输入框
  nextTick(() => {
    barcodeInputRef.value?.focus()
  })
  
  ElMessage.success('盘库数据已更新')
}

// 添加扫码历史
function addScanHistory(product: any, realQty: number) {
  scanHistory.value.unshift({
    id: Date.now(),
    timestamp: new Date().toLocaleString(),
    product: product.name,
    trackingNumber: product.trackingNumber,
    realQty,
    operator: auth.user?.name || '未知用户'
  })
  
  // 限制历史记录数量
  if (scanHistory.value.length > 100) {
    scanHistory.value = scanHistory.value.slice(0, 100)
  }
}

// 显示扫码历史
function showScanHistory() {
  scanHistoryDialog.value = {
    visible: true,
    data: scanHistory.value
  }
}

// 重置扫码输入
function resetBarcodeInput() {
  barcodeInput.value = ''
  lastScannedProduct.value = null
  scanCount.value = 0
  scanHistory.value = []
  ElMessage.success('扫码状态已重置')
}

// 播放扫码提示音
function playScanSound(success = true) {
  // 这里可以添加音频播放逻辑
  // const audio = new Audio()
  // audio.src = success ? '/sounds/scan-success.mp3' : '/sounds/scan-error.mp3'
  // audio.play()
}

// 设置键盘快捷键
function setupKeyboardShortcuts() {
  document.addEventListener('keydown', (event) => {
    // Ctrl + S：显示扫码历史
    if (event.ctrlKey && event.key === 's') {
      event.preventDefault()
      showScanHistory()
    }
    
    // Ctrl + R：重新开始扫码
    if (event.ctrlKey && event.key === 'r') {
      event.preventDefault()
      resetBarcodeInput()
    }
  })
}

// 页面加载时设置快捷键
setupKeyboardShortcuts()

// ========== 演示相关方法 ==========

// 显示演示条码弹窗
function showDemoBarcodes() {
  demoBarcodesDialog.value.visible = true
}

// 选择演示条码
function selectDemoBarcode(barcode: string) {
  barcodeInput.value = barcode
  // 自动聚焦到输入框
  nextTick(() => {
    barcodeInputRef.value?.focus()
  })
  ElMessage.success('条码已复制到输入框，请按回车键或点击模拟扫码')
}

// 模拟扫码
function simulateScan(barcode: string) {
  barcodeInput.value = barcode
  // 模拟扫码枪的回车键
  setTimeout(() => {
    processBarcode(barcode)
    barcodeInput.value = ''
  }, 100)
}

// 演示模式：自动开始盘点
function startDemoInventory() {
  if (!detailDialog.value.data) return
  
  // 自动开始盘点
  startInventory()
  
  // 显示演示提示
  ElMessage.success('演示模式已启动！请点击"演示条码"按钮开始体验扫码功能')
  
  // 自动聚焦到扫码输入框
  nextTick(() => {
    barcodeInputRef.value?.focus()
  })
}
</script>

<style scoped>
.inventory-manage-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.mb-3 { margin-bottom: 24px; }
.mb-2 { margin-bottom: 12px; }

/* 扫码输入区域样式 */
.barcode-input-area {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  border: 2px solid #e4e7ed;
}

.barcode-input {
  font-size: 18px;
  font-weight: bold;
}

.barcode-input :deep(.el-input__wrapper) {
  background: #fff;
  border: 2px solid #409eff;
}

.scan-status {
  margin-top: 8px;
  text-align: center;
}

.scan-actions {
  margin-top: 8px;
  text-align: center;
}

/* 快速输入弹窗样式 */
.scanned-product-info {
  background: #f0f9ff;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  border: 1px solid #b3d8ff;
}

/* 扫码历史样式 */
.scan-history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.scan-history-item:last-child {
  border-bottom: none;
}

/* 扫码状态高亮 */
.scan-highlight {
  background: #f0f9ff !important;
  border: 2px solid #409eff !important;
}

/* 演示条码样式 */
.demo-barcodes-content {
  padding: 16px;
}

.demo-tip {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.barcode-list {
  margin-top: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.barcode-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.barcode-item:hover {
  background: #f0f9ff;
  border-color: #409eff;
}

.barcode-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.barcode-code {
  font-family: 'Courier New', monospace;
  color: #606266;
  font-size: 12px;
  background: #fff;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .barcode-input-area {
    padding: 12px;
  }
  
  .barcode-input {
    font-size: 16px;
  }
  
  .barcode-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
.mt-3 { margin-top: 24px; }
.flex { display: flex; }
.items-center { align-items: center; }
.gap-2 { gap: 8px; }
</style> 